package sql.db;

import java.io.*;
import java.util.*;

import sql.exception.MyDBException;

public class Cartesian {

	public Cartesian() {
		super();
	}
	
	public String carTwo(String oriname1, String newname1, String oriname2, String newname2) throws Exception
	{	
		DBManager dbMng1;
		if (oriname1.contains(new String("cartesian.")))
			dbMng1 = new DBManager(oriname1.toLowerCase(), Main.env_path);
		else
			dbMng1 = new DBManager("tuples." + oriname1.toLowerCase(), Main.env_path);
		
		String resname;
		try {
			resname = dbMng1.cartesian(oriname1, newname1, oriname2, newname2);
		}
		catch (MyDBException ex) {
			dbMng1.close();
			throw ex;
		}
		catch (Exception ex) {
			dbMng1.close();
			throw ex;
		}
		
		dbMng1.close();
		
		if (oriname1.contains(new String("cartesian.")))
			new DBManager(oriname1, Main.env_path, true);
		if (oriname2.contains(new String("cartesian.")))
			new DBManager(oriname2, Main.env_path, true);
		
		
		return resname;
	}
	
	public String carAll(AliasTable aliasTable) throws Exception
	{
		if (aliasTable.size() == 1)
			return aliasTable.getOriName(0);
		
		String oriname1 = aliasTable.getOriName(0);
		String newname1 = aliasTable.getNewName(0);
		String oriname2 = aliasTable.getOriName(1);
		String newname2 = aliasTable.getNewName(1);
		
		String resname1 = carTwo(oriname1, newname1, oriname2, newname2);
		
		aliasTable.removeFirstTwo();
		aliasTable.insertFirst(resname1, resname1);
		
		return carAll(aliasTable);
	}
}
